<template lang="pug">
table.table(:class='tableClass')
  thead
    tr
      th(v-for='c in titles') {{c}}
  tbody
    tr(v-for='(item, index) in items')
      td(v-for='c in columns')
        div(:is='itemComp(c)', v-bind="itemValue(item, c, index)", v-on:delete="deleteItem")
  footer
    slot(name='footer')
</template>

<script>
import Vue from 'vue'

export default {
  name: 'md-table',
  components: {
    Plain: Vue.component('plain', {
      props: ['value'],
      template: `<span>{{value}}</span>`
    })
  },
  props: {
    columns: Array,
    titles: Array,
    items: Array,
    type: {
      type: String, // default | striped | hover
      default: ''
    }
  },
  computed: {
    tableClass() {
      return `table-${this.type}`
    }
  },
  methods: {
    deleteItem(idx) {
      this.items.splice(idx, 1)
    },
    itemComp(column) {
      let [, renderBy] = column.split(':')
      return renderBy || 'plain'
    },
    itemValue(item, column, index) {
      let [path] = column.split(':')
      if (!path) return {value: item, index}

      let value = path.split('.').reduce((prev, curr) => item[curr], item)
      return {value, index}
    }
  }
}

</script>
<style lang="scss"></style>
